<script setup>
    import { computed, ref } from 'vue'

    //商品列表
    const goodsList=ref([
      { id: 1,name: '篮球',num: 1},
      { id: 2,name: '玩具',num: 1},
      { id: 3,name: '书籍',num: 1}
    ])


    //计算属性：计算求得总数量
    const totalNum=computed(()=>{
      console.log('1-computed')
      //taotalNum是基于goodsList数组计算得到的，这里称goodsList为totalNum的依赖
      return goodsList.value.reduce((prev,item)=>prev+item.num,0)
    })

    //普通函数：求得总数量
    const calTotalNum=()=>{
      console.log('2-function')
      return goodsList.value.reduce((prev,item)=> prev+item.num,0)
    }

</script>

<template>
  <h3>比特人的礼物清单</h3>
  <table>
    <thead>
      <tr>
        <th>名字</th>
        <th>数量</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="item in goodsList" :key="item.id">
        <td>{{ item.name }}</td>
        <td>{{ item.num }}</td>
      </tr>
    </tbody>
  </table>
  <p>礼物总数: {{ totalNum }}个</p>
  <p>礼物总数: {{ totalNum }}个</p>
  <p>礼物总数: {{ totalNum }}个</p>
  <hr>

  <p>礼物总数:{{ calTotalNum()}}个</p>
  <p>礼物总数:{{ calTotalNum()}}个</p>
  <p>礼物总数:{{ calTotalNum()}}个</p>
</template>


<style scoped>
  table{
    width:350px;
    border:1px solid #333;
  }

  table th,table td{
    border:1px solid #333;
  }

  table td{
    text-align:center;
  }
</style>